<?php
/*
 * Copyright notice
 * 
 * (c) 2009 MH-Dev.de, Martin Hesse <info@mh-dev.de>
 * 
 * This script is part of the MH-Dev.-Board project. The MH-Dev.-Board 
 * is free software; you can redistribute it and/or modify it under the 
 * terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, 
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty 
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU 
 * General Public License along with this program; if not, 
 * see http://www.gnu.org/licenses/.
 */


/**
 * Login
 *
 * @author	Martin Hesse <info@mh-dev.de>
 * @package	MH-Dev.-Board
 */
class LoginController extends Zend_Controller_Action
{
	private $auth; // auth
	private $translate; // translation
	
	public function init()
	{
		// auth
		$this->auth = Zend_Auth::getInstance();
		
		// lang
		$this->translate		= Zend_Registry::get('lang');
		
		// assign translation to view
		$this->view->translate 	= $this->translate;
		
		// flash messenger
		$this->view->flashMessenger	= $this->_helper->FlashMessenger;
	}
	
	
	
	/*
	 * shows the login form and handle the data
	 * 
	 * @param null
	 * 
	 * @return Zend_View
	 */
	public function indexAction()
	{
		// db
		$threads 	= new Threads();
		$posts		= new Posts();
		
		// form
		$login = new LoginForm();
		
		$this->view->form = $login;

		if ($this->_request->isPost()) 
		{
			if($login->isValid($_POST))
			{
				$username 	= $this->_request->getPost('username');
				$password	= $this->_request->getPost('password');
		
				$user 	= new User();
				$check	= $user->fetchAll('uid > 0 AND mail="' . $username .'" AND is_active=1');
				
				if($check->count() > 0)
				{
					$getUser	= $check->toArray();
					$save_login = $this->_request->getPost('save') ? true : false;

					if($getUser[0]['bad_login_date'] > time())
					{
						$this->view->errorMessage = MHDEV_Sprintf(
							$this->translate->_('login_error3'),
							array(
								'%date' => date('d.m.Y, G:i:s', $getUser[0]['bad_login_date'])
							));
					}
					// if bad logins about N
					// @FIXME: replace 3 with a value from the board settings
					elseif($getUser[0]['bad_logins'] >= 3)
					{
						// write date of max bad logins in the user database
						$user->update(array('bad_login_date' => time()+(60*5), 'bad_logins' => 0), 'mail="' . $username . '" AND is_active = 1');
					}
					else
					{
						if($this->auth($username, $password, $save_login))
						{
							// recount all posts and threads of a user
							$getThreads	= $threads->fetchAll('is_deleted = 0 AND is_public = 1 AND user_uid =' . $this->auth->getIdentity()->uid);
							$getPosts	= $posts->fetchAll('is_deleted = 0 AND is_public = 1 AND user_uid=' . $this->auth->getIdentity()->uid);
							
							$user->update(array(
								'count_threads'	=> $getThreads->count(),
								'count_posts'	=> $getPosts->count()
							), 'uid=' . $this->auth->getIdentity()->uid);
				
							$this->loginSuccessfull();
						} 
						else 
						{
							$this->view->errorMessage = $this->translate->_('login_error');
						}
					}
				}
				else
				{
					$this->view->errorMessage = $this->translate->_('login_error2');
				}
			}
			else
			{
				$login->populate($_POST);
			}
		}
	}
	
	
	
	/*
	 * Authenticate a user with his username and password
	 * Returns true if successfull
	 * 
	 * @param string $username
	 * @param string $password
	 * @param boolean $save
	 * 
	 * @return boolean
	 */
	protected function auth($username, $password, $save = FALSE)
	{
		// db
		$user	= new User();
		
		// authadapter
		$authAdapter = new Zend_Auth_Adapter_DbTable(
			Zend_Registry::get('db'), 
			'user', 
			'mail', 
			'password', 
			'MD5(?)'
		);
		
		$authAdapter->setIdentity($username);
		$authAdapter->setCredential($password);
		
		$result = $authAdapter->authenticate();
		
		if($result->isValid()) 
		{
			if($save)
			{
				// generate hash
				$hash1 = uniqid(md5(time()),true);
				$hash2 = uniqid(md5(time()),true);
				
				// write hash to user database
				$user->update(array('hash1' => $hash1, 'hash2' => $hash2),'mail="' . $username . '" AND is_active = 1');
				
				// add cookies
				setcookie("mhdev_hash1", $hash1, time()+60*60*24*31);
				setcookie("mhdev_hash2", $hash2, time()+60*60*24*31);
			}
			
			// write auth in to the storage
			$this->auth->getStorage()->write($authAdapter->getResultRowObject(null, 'password'));

			return true;
		}
		else
		{
			// log a bad login ...
			$user->update(array('bad_logins' => new Zend_Db_Expr('bad_logins+1')),'mail="' . $username . '" AND is_active = 1');
		}
	}
	
	
	
	/*
	 * Action after a successfull login ...
	 * 
	 * @param null
	 * 
	 * @return redirect
	 */
	public function loginSuccessfull()
	{
		return $this->_redirect('/');
	}
	
	
	
	/*
	 * logout a user and redirect to the startpage
	 */
	public function logoutAction() 
	{	
		$this->auth->clearIdentity();
		$this->_helper->FlashMessenger($this->translate->_('flash_logout'));
		
		return $this->logoutSuccessfull();
	}
	
	
	
	/*
	 * Action after a successfull logout ...
	 * 
	 * @param null
	 * 
	 * @return redirect
	 */
	public function logoutSuccessfull()
	{
		return $this->_redirect('/');
	}
}
?>